<template>
  <div class="sensitive-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>敏感词管理</span>
          <el-button type="primary" @click="handleAdd">新增敏感词</el-button>
        </div>
      </template>

      <!-- 敏感词列表 -->
      <el-table
        v-loading="loading"
        :data="sensitiveList"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="word" label="敏感词" min-width="150" />
        <el-table-column prop="level" label="级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTag(row.level)">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 敏感词表单对话框 -->
    <el-dialog
      title="新增敏感词"
      v-model="dialogVisible"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="sensitiveFormRef"
        :model="sensitiveForm"
        :rules="sensitiveRules"
        label-width="100px"
      >
        <el-form-item label="敏感词" prop="word">
          <el-input
            v-model="sensitiveForm.word"
            placeholder="请输入敏感词"
            :maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-select v-model="sensitiveForm.level" placeholder="请选择级别">
            <el-option label="低" :value="1" />
            <el-option label="中" :value="2" />
            <el-option label="高" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="sensitiveForm.category" placeholder="请选择分类">
            <el-option label="政治" value="POLITICAL" />
            <el-option label="色情" value="PORN" />
            <el-option label="暴力" value="VIOLENCE" />
            <el-option label="广告" value="AD" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="sensitiveForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注（选填）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getSensitiveWords,
  addSensitiveWord,
  deleteSensitiveWord
} from '@/api/admin'

// 状态定义
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const sensitiveList = ref([])
const sensitiveFormRef = ref(null)

// 表单数据
const sensitiveForm = ref({
  word: '',
  level: undefined,
  category: '',
  remark: ''
})

// 表单校验规则
const sensitiveRules = {
  word: [
    { required: true, message: '请输入敏感词', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择级别', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

// 获取敏感词列表
const fetchSensitiveWords = async () => {
  try {
    loading.value = true
    const res = await getSensitiveWords()
    
    if (res?.code === 200) {
      sensitiveList.value = res.data
    } else {
      ElMessage.warning(res?.message || '获取敏感词列表失败')
    }
  } catch (error) {
    console.error('获取敏感词列表失败:', error)
    ElMessage.error('获取敏感词列表失败')
  } finally {
    loading.value = false
  }
}

// 新增敏感词
const handleAdd = () => {
  sensitiveForm.value = {
    word: '',
    level: undefined,
    category: '',
    remark: ''
  }
  dialogVisible.value = true
}

// 删除敏感词
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该敏感词吗？', '警告', {
      type: 'warning'
    })
    
    const res = await deleteSensitiveWord(row.id)
    if (res?.code === 200) {
      ElMessage.success('删除成功')
      fetchSensitiveWords()
    } else {
      ElMessage.error(res?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除敏感词失败:', error)
      ElMessage.error('删除敏感词失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  if (!sensitiveFormRef.value) return
  
  try {
    await sensitiveFormRef.value.validate()
    submitting.value = true
    
    const res = await addSensitiveWord(sensitiveForm.value)
    if (res?.code === 200) {
      ElMessage.success('添加成功')
      dialogVisible.value = false
      fetchSensitiveWords()
    } else {
      ElMessage.error(res?.message || '添加失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('提交失败：' + (error.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}

// 获取级别标签类型
const getLevelTag = (level) => {
  const tags = {
    1: 'info',
    2: 'warning',
    3: 'danger'
  }
  return tags[level] || ''
}

// 获取级别文本
const getLevelText = (level) => {
  const texts = {
    1: '低',
    2: '中',
    3: '高'
  }
  return texts[level] || level
}

// 格式化日期
const formatDate = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray)) return '暂无'
  const [year, month, day, hour, minute, second] = dateArray
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`
}

// 初始化
onMounted(() => {
  fetchSensitiveWords()
})
</script>

<style scoped>
.sensitive-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-select) {
  width: 100%;
}
</style> 